/**
 * Copyright &copy; 2013-2015 山东易科德软件有限公司 All rights reserved.
 */
package cn.net.ecode.modules.sys.security;

import java.io.Serializable;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import javax.annotation.PostConstruct;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.stereotype.Service;

import cn.net.ecode.common.config.Global;
import cn.net.ecode.common.mapper.JsonMapper;
import cn.net.ecode.common.security.Digests;
import cn.net.ecode.common.security.shiro.session.SessionDAO;
import cn.net.ecode.common.servlet.ValidateCodeServlet;
import cn.net.ecode.common.utils.DateUtils;
import cn.net.ecode.common.utils.Encodes;
import cn.net.ecode.common.utils.SpringContextHolder;
import cn.net.ecode.common.utils.StringUtils;
import cn.net.ecode.common.web.Servlets;
import cn.net.ecode.modules.sys.entity.Menu;
import cn.net.ecode.modules.sys.entity.Role;
import cn.net.ecode.modules.sys.entity.User;
import cn.net.ecode.modules.sys.service.UserService;
import cn.net.ecode.modules.sys.utils.LogUtils;
import cn.net.ecode.modules.sys.utils.UserUtils;
import cn.net.ecode.modules.sys.web.LoginController;

/**
 * 系统安全认证实现类
 * @author ThinkGem
 * @version 2015-2-3
 */
@Service
//@DependsOn({"userDao","roleDao","menuDao"})
public class AuthorizingRealm extends org.apache.shiro.realm.AuthorizingRealm {

//	private Logger logger = LoggerFactory.getLogger(getClass());
	
	private SessionDAO sessionDao;
	private UserService userService;

//	private static Map<String, String> keyInfo;
//	private static Date keyLastUpdateDate = new Date();

	/**
	 * 认证回调函数, 登录时调用
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) {
		UsernamePasswordToken token = (UsernamePasswordToken) authcToken;

		// 如果使用了集团用户模式，则获取集团Code
		String corpCode = null;
		if (Global.isUseCorpModel()){
			if (StringUtils.isNotBlank(token.getParams())){
				Map<String, Object> map = JsonMapper.fromJsonString(token.getParams(), Map.class);
				if (map != null){
					corpCode = (String)map.get("corpCode");
				}
			}
			if (StringUtils.isBlank(corpCode)){
				throw new AuthenticationException("msg:请选择您要登录的集团公司.");
			}
		}
		
		// 校验登录验证码
		if (LoginController.isValidateCodeLogin(token.getUsername(), corpCode, false, false)){
			Session session = UserUtils.getSession();
			String code = (String)session.getAttribute(ValidateCodeServlet.VALIDATE_CODE);
			if (token.getCaptcha() == null || !token.getCaptcha().toUpperCase().equals(code)){
				throw new AuthenticationException("msg:验证码错误, 请重试.");
			}
		}
		
//		// 校验最大在线用户数
//		Map<String, String> keyInfo = AuthorizingRealm.getKeyInfo();
//		int maxOnlineUserNum = 0;
//		try{
//			maxOnlineUserNum = Integer.valueOf(keyInfo.get("maxOnlineUserNum"));
//		}catch (Exception e) {
//			throw new AuthenticationException("msg:" + Encodes.decodeBase64String("5o6I5p2D5paH5Lu25peg5pWI77yM6K+36IGU57O75a6i5pyNLiA=") + AuthorizingRealm.getKeyCodeMessage());
//		}
//		int activeSessionSize = getSessionDao().getActiveSessions(false).size();
//		if (logger.isDebugEnabled()){
//			logger.debug("login submit, active session size: {}, username: {}", activeSessionSize, token.getUsername());
//		}
//		if (activeSessionSize >= maxOnlineUserNum){
//			throw new AuthenticationException("msg:" + Encodes.decodeBase64String("5oKo55qE5pyA5aSn5Zyo57q/55So5oi35pWw5Li6IOKAnA==") 
//					+ maxOnlineUserNum  + Encodes.decodeBase64String("4oCdIOS4qu+8jOWmgumcgOeUs+ivt+WinuWKoO+8jOivt+iBlOezu+Wuouacje+8gQ==") + AuthorizingRealm.getKeyCodeMessage());
//		}
		
		// 校验用户名密码
		User user = UserUtils.getByLoginCode(token.getUsername(), corpCode);
		
		if (user != null) {
			if (!User.STATUS_NORMAL.equals(user.getStatus())){
				if (User.STATUS_DISABLE.equals(user.getStatus())){
					throw new AuthenticationException("msg:该帐号已停用.");
				}else if (User.STATUS_FREEZE.equals(user.getStatus())){
					throw new AuthenticationException("msg:该帐号已冻结.");
				}else if (User.STATUS_AUDIT.equals(user.getStatus())){
					throw new AuthenticationException("msg:该帐号未审核.");
				}else{
					throw new AuthenticationException("msg:该帐号无效.");
				}
			}else{
				byte[] salt = Encodes.decodeHex(user.getPassword().substring(0,16));
				return new SimpleAuthenticationInfo(new Principal(user, token.getParams()), 
						user.getPassword().substring(16), ByteSource.Util.bytes(salt), getName());
			}
		}
		return null;
	}
	
	/**
	 * 授权查询回调函数, 进行鉴权但缓存中无用户的授权信息时调用
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		Principal principal = (Principal) getAvailablePrincipal(principals);
		// 获取当前已登录的用户
		if (!StringUtils.toBoolean(Global.getConfig("user.multiAccountLogin"))){
			Collection<Session> sessions = getSessionDao().getActiveSessions(true, principal, UserUtils.getSession());
			if (sessions.size() > 0){
				// 如果是登录进来的，则踢出已在线用户
				if (UserUtils.getSubject().isAuthenticated()){
					for (Session session : sessions){
						getSessionDao().delete(session);
					}
				}
				// 记住我进来的，并且当前用户已登录，则退出当前用户提示信息。
				else{
					UserUtils.getSubject().logout();
					throw new AuthenticationException("msg:账号已在其它地方登录，请重新登录。");
				}
			}
		}
		User user = UserUtils.get(principal.getId());
		if (user != null) {
			SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
			List<Menu> list = UserUtils.getMenuList();
			for (Menu menu : list){
				if (StringUtils.isNotBlank(menu.getPermission())){
					// 添加基于Permission的权限信息
					for (String permission : StringUtils.split(menu.getPermission(),",")){
						info.addStringPermission(permission);
					}
				}
			}
			/*// 添加临时验证权限
			info.addStringPermission("gen");
			info.addStringPermission("sys");
			info.addStringPermission("cms");
			info.addStringPermission("act");
			info.addStringPermission("test");*/
			// 添加用户权限
			info.addStringPermission("user");
			// 添加用户角色信息
			for (Role role : user.getRoleList()){
				info.addRole(role.getRoleCode());
			}
			// 更新登录IP和时间
			getUserService().updateUserLoginInfo(user);
			// 记录用户登录日志
			LogUtils.saveLog(Servlets.getRequest(), "系统登录");
			// 登录成功后扩展处理的方法 
			try{
				LoginFollow loginFollow = SpringContextHolder.getBean("loginFollow");
				if(loginFollow != null){
					loginFollow.loginSucess(user);
				}
			}catch(Exception e){
				
			}
			return info;
		} else {
			return null;
		}
	}

	/**
	 * 认证密码匹配调用方法
	 */
	@Override
	protected void assertCredentialsMatch(AuthenticationToken authcToken,
			AuthenticationInfo info) throws AuthenticationException {
		UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
		// 若单点登录，则使用单点登录授权方法。
		if (token.toString().equals(token.getParams())){
			// sso密钥+用户名+日期，进行md5加密，举例： Digests.md5(secretKey+username+20150101)）
			String secretKey = Global.getConfig("shiro.sso.secretKey");
			String password = Digests.md5(secretKey + token.getUsername() + DateUtils.getDate("yyyyMMdd"));
			if (password.equals(String.valueOf(token.getPassword()))){
				return;
			}
		}
		super.assertCredentialsMatch(token, info);
	}
	
	/**
	 * 设定密码校验的Hash算法与迭代次数
	 */
	@PostConstruct
	protected void initCredentialsMatcher() {
		HashedCredentialsMatcher matcher = new HashedCredentialsMatcher(UserService.HASH_ALGORITHM);
		matcher.setHashIterations(UserService.HASH_INTERATIONS);
		setCredentialsMatcher(matcher);
	}
	
//	@Override
//	protected void checkPermission(Permission permission, AuthorizationInfo info) {
//		authorizationValidate(permission);
//		super.checkPermission(permission, info);
//	}
//	
//	@Override
//	protected boolean[] isPermitted(List<Permission> permissions, AuthorizationInfo info) {
//		if (permissions != null && !permissions.isEmpty()) {
//            for (Permission permission : permissions) {
//        		authorizationValidate(permission);
//            }
//        }
//		return super.isPermitted(permissions, info);
//	}
//	
//	@Override
//	public boolean isPermitted(PrincipalCollection principals, Permission permission) {
//		authorizationValidate(permission);
//		return super.isPermitted(principals, permission);
//	}
//	
//	@Override
//	protected boolean isPermittedAll(Collection<Permission> permissions, AuthorizationInfo info) {
//		if (permissions != null && !permissions.isEmpty()) {
//            for (Permission permission : permissions) {
//            	authorizationValidate(permission);
//            }
//        }
//		return super.isPermittedAll(permissions, info);
//	}
//	
//	/**
//	 * 授权验证方法
//	 * @param permission
//	 */
//	private void authorizationValidate(Permission permission){
//		Map<String, String> keyInfo = AuthorizingRealm.getKeyInfo();
//    	try{
//    		boolean success = false;
//        	if (StringUtils.startsWith(permission.toString(), "[user]")){
//        		success = true;
//        	}else if (StringUtils.equals(keyInfo.get("openModules"), "all")){
//        		success = true;
//        	}else{
//        		for (String s : StringUtils.split(keyInfo.get("openModules"), ",")){
//            		if (StringUtils.startsWith(permission.toString(), "["+s+"]")){
//            			success = true;
//            		}
//            	}
//        	}
//        	if (!success){
//        		throw new UnauthorizedException("msg:" + Encodes.decodeBase64String("5b2T5YmN5qih5Z2X5rKh5pyJ5o6I5p2D77yM5aa" +
//        				"C6ZyA6LSt5Lmw6K+36IGU57O75a6i5pyN77yBPGJyLz4gPGJyLz4g5oKo55qE5py65Zmo56CB5piv77ya") + keyInfo.get("code"));
//        	}
//    	}catch (Exception e) {
//    		throw new UnauthorizedException("msg:" + Encodes.decodeBase64String("6I635Y+W5qih5Z2X5o6I5p2D5aSx6LSl77yM6K+36IGU" +
//    				"57O75a6i5pyN77yBPGJyLz4gPGJyLz4g5oKo55qE5py65Zmo56CB5piv77ya") + keyInfo.get("code"));
//		}
//	}
	
	/**
	 * 清空用户关联权限认证，待下次使用时重新加载
	 */
	public void clearCachedAuthorizationInfo(String principal) {
		SimplePrincipalCollection principals = new SimplePrincipalCollection(principal, getName());
		clearCachedAuthorizationInfo(principals);
	}

	/**
	 * 清空所有关联认证
	 */
	public void clearAllCachedAuthorizationInfo() {
		Cache<Object, AuthorizationInfo> cache = getAuthorizationCache();
		if (cache != null) {
			for (Object key : cache.keys()) {
				cache.remove(key);
			}
		}
	}
	
	/**
	 * 授权用户信息
	 */
	public static class Principal implements Serializable {

		private static final long serialVersionUID = 1L;
		
		private String id;
		private String name;
		private Map<String, Object> params; 

		/**
		 * 构造方法
		 * @param user 登录用户对象
		 * @param params 登录预留参数，格式 JSON 字符串
		 */
		public Principal(User user, String params) {
			this.id = user.getUserCode();
			this.name = user.getUserName();
			if (StringUtils.isNotBlank(params)){
				this.params = JsonMapper.fromJsonString(params, Map.class);
			}
		}

		/**
		 * 用户编码，userCode
		 */
		public String getId() {
			return id;
		}

		/**
		 * 用户名称，userName
		 */
		public String getName() {
			return name;
		}
		
		/**
		 * 获取登录时提交的参数
		 */
		public String getParam(String key) {
			if (params != null){
				Object value = params.get(key);
				if (value != null){
					return value.toString();
				}
			}
			return null;
		}

		/** 
		 * 重载toString，只输出id
		 */
		@Override
		public String toString() {
			return id;
		}

		/** 
		 * 重载hashCode，只计算id
		 */
		@Override
		public int hashCode() {
			return Objects.hashCode(id);
		}

		/** 
		 * 重载equals，只计算id
		 */
		@Override
		public boolean equals(Object obj) {
			if (this == obj){
				return true;
			}
			if (obj == null){
				return false;
			}
			if (getClass() != obj.getClass()){
				return false;
			}
			Principal other = (Principal) obj;
			if (getId() == null) {
				if (other.getId() != null){
					return false;
				}
			} else if (!getId().equals(other.getId())){
				return false;
			}
			return true;
		}
		
	}

//	/**
//	 * Key
//	 * @return
//	 */
//	@SuppressWarnings("unchecked")
//	public static Map<String, String> getKeyInfo(){
//		if (keyInfo != null && DateUtils.pastDays(keyLastUpdateDate) == 0){
//			return keyInfo;
//		}
//		keyLastUpdateDate = new Date();
//		int len = 70;
//		FileInputStream inputStream = null;
//		String code = Encodes.encodeHex(Digests.md5(MacUtils.getMac().getBytes(), 90));
//		try{
//			String fileName = new DefaultResourceLoader().getResource("").getFile().getParent() 
//					+ File.separator + 'e' + 'c' + 'o' + 'd' + 'e' + '.' + 'c' + 'e' + 'r';
//			File file = new File(fileName);
//			if (!file.exists()){
//				if (FileUtils.createFile(fileName)){
//					FileOutputStream outputStream = null;
//					try{
//						keyInfo = new HashMap<String, String>();
//						keyInfo.put("code", code);
//						keyInfo.put("expireDate", DateUtils.formatDate(DateUtils.addDays(new Date(), 20), "yyyy-MM-dd"));
//						keyInfo.put("maxRegUserNum", "200");
//						keyInfo.put("maxOnlineUserNum", "50");
//						keyInfo.put("openModules", "all");
//						String json = JsonMapper.toJsonString(keyInfo);
//						outputStream = FileUtils.openOutputStream(file);
//						for (int i = 0; i < 8; i++){
//							outputStream.write(Cryptos.generateAesKey());
//						}
//						byte[] key = Cryptos.generateAesKey();
//						outputStream.write(key);
//						byte[] data = Cryptos.aesEncrypt(json.getBytes(), key);
//						outputStream.write(data);
//					}catch (Exception e) {
//						e.printStackTrace();
//					}finally{
//						try {
//							if (outputStream != null){
//								outputStream.close();
//							}
//						} catch (IOException e) {
//							// 什么也不用做
//						}
//					}
//				}
//			}
//			if (file.exists()){
//				inputStream = FileUtils.openInputStream(file);
//				byte[] tmp = new byte[16 * 8];
//				inputStream.read(tmp);
//				byte[] key = new byte[16];
//				inputStream.read(key);
//				byte[] data = new byte[(int)file.length() - tmp.length - key.length];
//				inputStream.read(data);
//				String json = new String(Cryptos.aesDecrypt(data, key));
//				keyInfo = (Map<String, String>)JsonMapper.fromJsonString(json, Map.class);
//				if ("dev".equals(keyInfo.get("code"))){
//					keyInfo.put("code", code);
//				}
//				if (code.equals(keyInfo.get("code"))){
//					String expireDate = keyInfo.get("expireDate");
//					Date date = DateUtils.parseDate(expireDate);
//					long t = date.getTime() - new Date().getTime();
//					long hour = t/(60*60*1000), day = hour/24;
//					StringBuffer sb = new StringBuffer();
//					sb.append("\r\n");
//					for(int i=0; i<len; i++){
//						sb.append("=");
//					}
//					if (hour <= 0){
//						throw new Exception(Encodes.decodeBase64String("5o6I5p2D5bCG6KaB5bey5Yiw5pyf77yM6K+35bC95b+r6IGU57O75a6i5pyN77yB"));
//					}else if (day <= 60){
//						sb.append("\r\n\r\n     " + Encodes.decodeBase64String("5o6I5p2D5bCG6KaB5Yiw5pyf77yM6L+Y5Ymp5L2Z"));
//						sb.append(day);
//						sb.append(Encodes.decodeBase64String("5aSp77yM5Li65LqG5LiN5b2x5ZON5oKo55qE5L2/55So77yM6K+35bC95b+r6IGU57O75a6i5pyN77yB"));
//					}else{
//						sb.append("\r\n\r\n     " + Encodes.decodeBase64String("5oSf6LCi5oKo55qE5L2/55So77yM5o6I5p2D5Yiw5pyf5pe26Ze05Li677ya"));
//						sb.append(DateUtils.formatDate(date, Encodes.decodeBase64String("eXl5eeW5tE1N5pyIZGTml6U=")));
//					}
//					sb.append("\r\n\r\n     " + Encodes.decodeBase64String("5pyA5aSn5rOo5YaM55So5oi35pWw77ya"));
//					sb.append((String)keyInfo.get("maxRegUserNum"));
//					sb.append("  " + Encodes.decodeBase64String("5pyA5aSn5Zyo57q/55So5oi35pWw77ya"));
//					sb.append((String)keyInfo.get("maxOnlineUserNum"));
//					sb.append("  " + Encodes.decodeBase64String("5byA5ZCv5qih5Z2X77ya"));
//					sb.append((String)keyInfo.get("openModules"));
//					sb.append("\r\n\r\n     ");
//					sb.append(Encodes.decodeBase64String("5oKo55qE5py65Zmo56CB5piv77ya"));
//					sb.append((String)keyInfo.get("code"));
//					sb.append("\r\n\r\n");
//					for(int i=0; i<len; i++){
//						sb.append("=");
//					}
//					sb.append("\r\n");
//					keyInfo.put("loadMessage", sb.toString());
//					return keyInfo;
//				}else{
//					throw new Exception(Encodes.decodeBase64String("5o6I5p2D5paH5Lu25peg5pWI77yM6K+36IGU57O75a6i5pyN6I635Y+W5o6I5p2D5paH5Lu244CC"));
//				}
//			}else{
//				throw new Exception(Encodes.decodeBase64String("5o6I5p2D5paH5Lu25LiN5a2Y5Zyo77yM6K+36IGU57O75a6i5pyN6I635Y+W5o6I5p2D5paH5Lu244CC"));
//			}
//		}catch (Exception e) {
//			StringBuffer sb = new StringBuffer();
//			sb.append("\r\n");
//			for(int i=0; i<len; i++){
//				sb.append("=");
//			}
//			sb.append("\r\n\r\n     ");
//			sb.append(e.getMessage());
//			sb.append("\r\n\r\n     ");
//			sb.append(Encodes.decodeBase64String("5oKo55qE5py65Zmo56CB5piv77ya"));
//			sb.append(code);
//			sb.append("\r\n\r\n");
//			for(int i=0; i<len; i++){
//				sb.append("=");
//			}
//			sb.append("\r\n\r\n");
//			keyInfo = new HashMap<String, String>();
//			keyInfo.put("code", code);
//			keyInfo.put("loadError", "true");
//			keyInfo.put("loadMessage", sb.toString());
//			return keyInfo;
//		}finally{
//			try {
//				if (inputStream != null){
//					inputStream.close();
//				}
//			} catch (IOException e) {
//			}
//		}
//	}
//
//	/**
//	 * 获取机器妈
//	 */
//	public static String getKeyCodeMessage(){
//		return Encodes.decodeBase64String("5oKo55qE5py65Zmo56CB5piv77ya") + getKeyInfo().get("code");
//	}
//	
//	/**
//	 * 获取Key加载信息
//	 */
//	public static boolean printKeyLoadMessage(){
//		System.out.println(getKeyInfo().get("loadMessage"));
//		return !"true".equals(getKeyInfo().get("loadError"));
//	}
	
	/**
	 * 获取用户业务对象
	 */
	public UserService getUserService() {
		if (userService == null){
			userService = SpringContextHolder.getBean(UserService.class);
		}
		return userService;
	}

	/**
	 * 获取SessionDAO
	 * @return
	 */
	public SessionDAO getSessionDao() {
		if (sessionDao == null){
			sessionDao = SpringContextHolder.getBean(SessionDAO.class);
		}
		return sessionDao;
	}
}
